<template>
  <div class="container">
    <div class="header">
      <h1>编辑商品</h1>
    </div>
    
    <el-card class="form-card" v-loading="loading">
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px" 
        class="product-form"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品图片" prop="imageUrl">
          <el-upload
            action="#"
            list-type="picture-card"
            :limit="1"
            :file-list="fileList"
            :auto-upload="false"
            :on-change="handleImageChange"
            accept="image/jpeg,image/png,image/gif"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div v-if="form.imageUrl" class="image-preview-container">
            <el-image 
              :src="form.imageUrl" 
              class="image-preview"
              :preview-src-list="[form.imageUrl]"
              preview-teleported
              fit="cover">
            </el-image>
          </div>
        </el-form-item>
        
        <el-form-item label="商品所需积分" prop="points">
          <el-input-number v-model="form.points" :min="0" :precision="0" :step="1" />
        </el-form-item>
        
        <el-form-item label="商品库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" :precision="0" :step="1" />
        </el-form-item>
        
        <el-form-item label="商品状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="true"
            :inactive-value="false"
            active-text="上架"
            inactive-text="下架"
          />
        </el-form-item>
        
        <el-form-item label="商品详情" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="5" 
            placeholder="请输入商品详情"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { uploadFile } from '@/api/upload'
import { updateProduct, getProductById } from '@/api/product'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const fileList = ref([])
const loading = ref(false)
const submitting = ref(false)
const productId = route.params.id
const imageFile = ref(null)

const form = reactive({
  name: '',
  imageUrl: '',
  points: 0,
  stock: 0,
  status: 1,
  description: ''
})

const rules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  points: [
    { required: true, message: '请输入商品积分', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ]
})

// 获取商品详情
const fetchProductDetail = async () => {
  loading.value = true
  try {
    console.log('获取商品详情，ID:', productId)
    
    if (!productId) {
      ElMessage.error('缺少商品ID参数')
      router.push('/product')
      return
    }
    
    // 调用真实API获取商品详情
    const res = await getProductById(productId)
    console.log('商品详情API返回:', res)
    
    if (res && res.code === 200 && res.data) {
      // 填充表单数据
      const productData = res.data
      
      // 确保ID被正确设置
      form.id = productId
      
      // 映射其他字段
      form.name = productData.name || ''
      form.imageUrl = productData.imageUrl || ''
      form.points = productData.points || 0
      form.stock = productData.stock || 0
      form.description = productData.description || ''
      
      // status可能是1/0或true/false，转换为布尔值供前端使用
      form.status = productData.status === 1 || productData.status === true
      
      console.log('处理后的表单数据:', form)
      
      // 设置图片预览
      if (form.imageUrl) {
        fileList.value = [
          { name: 'product-image', url: form.imageUrl }
        ]
      }
    } else {
      ElMessage.error(res?.message || '获取商品详情失败')
    }
  } catch (error) {
    ElMessage.error('获取商品详情失败: ' + (error.message || '未知错误'))
    console.error('获取商品错误:', error)
  } finally {
    loading.value = false
  }
}

// 处理图片选择不立即上传
const handleImageChange = (file) => {
  imageFile.value = file.raw
  
  // 本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    // 显示本地预览图（上传成功前的临时显示）
    form.imageUrl = e.target.result
  }
  reader.readAsDataURL(imageFile.value)
}

const submitForm = async () => {
  const valid = await formRef.value.validate().catch(() => false)
  
  if (!valid) return
  
  submitting.value = true
  try {
    // 如果有选择新图片，先上传图片
    if (imageFile.value) {
      const res = await uploadFile(imageFile.value, 'product')
      if (res && res.code === 200) {
        form.imageUrl = `http://localhost:8080/api`+res.message // 后端返回的图片URL
        ElMessage.success('图片上传成功')
      } else {
        throw new Error(res?.message || '图片上传失败')
      }
    }
    
    // 确保status是数字类型，后端需要0或1
    form.status = form.status ? 1 : 0
    
    console.log('提交的商品数据:', form)
    
    // 调用真实API更新商品
    const response = await updateProduct(form)
    console.log('更新商品返回结果:', response)
    
    if (response && response.code === 200) {
      ElMessage.success('商品更新成功')
      router.push('/product')
    } else {
      throw new Error(response?.message || '更新失败')
    }
  } catch (error) {
    console.error('更新商品失败', error)
    ElMessage.error('商品更新失败：' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

const cancel = () => {
  router.push('/product')
}

onMounted(() => {
  fetchProductDetail()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  
  .header {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
  }
  
  .form-card {
    margin-bottom: 20px;
  }
  
  .product-form {
    max-width: 600px;
    margin-top: 20px;
    
    .image-preview-container {
      margin-top: 10px;
      text-align: center;
      
      .image-preview {
        width: 200px;
        height: 200px;
        object-fit: cover;
        border-radius: 4px;
      }
    }
  }
}
</style>